package org.example.myleet.p386;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> lexicalOrder(int n) {
        List<Integer> result = new ArrayList<>(n);
        dfs(1, result, n, 1);
        return result;
    }

    private void dfs(int num, List<Integer> result, int n, int tailNum) {
        result.add(num);
        int nextNum = num * 10;
        if (nextNum <= n) {
            dfs(nextNum, result, n, 0);
        }
        nextNum = num + 1;
        if (tailNum < 9 && nextNum <= n) {
            dfs(nextNum, result, n, ++tailNum);
        }
    }
}
